package com.opc.work;

import com.opc.config.OpcClientConfigBean;
import com.opc.dto.SelectData;
import com.opc.service.DeviceService;
import com.opc.utils.OpcClient;
import com.opc.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author SEG
 */
@Slf4j
@Component
public class OpcStatusCheckSchedule {
    @Resource
    private RedisUtils redisUtils;
    @Autowired
    private OpcClientConfigBean clientConfigBean;

    @Autowired
    private DeviceService deviceService;

    /**
     * 检测设备状态的接口，每3小时检测一次
     */
//    @Scheduled(cron = "0/10 * * * * ?")
//    @Scheduled(cron = "0 0 0/3 * * ?")
//    @Scheduled(cron = "0 0/30 * * * ?")
    public void consumeReading() {
        OpcClient opcClient = new OpcClient();
        List<SelectData> productLine = deviceService.getProductLine();
        HashMap<String, Integer> map = new HashMap<>();
        for (SelectData selectData : productLine) {
            map.put(selectData.getValue(), 0);
        }
        boolean ret = opcClient.connectServer(clientConfigBean.getIp(), clientConfigBean.getClsid(), clientConfigBean.getUser(), clientConfigBean.getPassword(), clientConfigBean.getDomain());
        if (!ret) {
            fillStatus(map, 0);
            log.error("connect opc server fail, opc server may not start, please check it in time");
            return;
        }
        Collection<String> itemIdList = new ArrayList<>();
        List<Object> keyList = redisUtils.lRange("key_list", 0, -1);
        keyList.forEach(key -> itemIdList.add(String.valueOf(key)));
        Collection<String> allItemList = opcClient.ALLItemList();
        if (allItemList == null || allItemList.isEmpty()) {
            fillStatus(map, 0);
            return;
        }
        List<String> divList = itemIdList.stream().filter(e -> !allItemList.contains(e)).collect(Collectors.toList());
        if (!divList.isEmpty()) {
            for (String div : divList) {
                String x = div.split("\\.")[1];
                if (map.containsKey(x)) {
                    redisUtils.set(x, map.get(x));
                }
            }
            return;
        } else {
            fillStatus(map, 1);
        }

    }

    private void fillStatus(HashMap<String, Integer> map, Integer status) {
        for (String p : map.keySet()) {
            redisUtils.set(p, status);
        }
    }

}



